package com.asj;

import static com.asj.enums.DeviceIdentifierDictEnums.json_key_deviceCode;
import static com.asj.enums.HttpRequestDictEnums.receiveTimedTask;
import static com.asj.enums.ResultCodeEnums.result_error;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;


import com.asj.mq.ReceiveMessageTask;
import com.asj.receiver.AppInstallReceiver;
import com.asj.receiver.NetworkChangeReceiver;
import com.asj.service.StayAliveService;
import com.asj.service.oppoSdk.OPPOSDKService;
import com.asj.utils.CommonsUtils;
import com.asj.utils.HttpRequestUtils;
import com.asj.utils.JSONParamPackingUtils;
import com.google.gson.JsonObject;

import java.util.Objects;

public class MainActivityService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private static final int NOTIFICATION_ID = 1;

    @Override
    public void onCreate() {
        super.onCreate();
        try{
            createNotification();
        }catch (Exception e){
            Log.e("创建后台服务通知异常：：", Objects.requireNonNull(e.getMessage()));
        }
    }

    /**
     * 创建前台服务通知
     * */
    public void createNotification(){
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        // 创建一个通知渠道，这是Android 8.0及以上版本要求的
        CharSequence name = "child_custody";
        String description = "监管服务";
        //IMPORTANCE_NONE 不会有通知显示以及声音提示
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        NotificationChannel channel = new NotificationChannel("child_custody_id", name, importance);
        channel.setDescription(description);
        notificationManager.createNotificationChannel(channel);

        // 创建通知
        Notification notification = new NotificationCompat.Builder(this, "child_custody_id")
                .setContentTitle("监管服务运行中")
                .setContentText("运行中")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT) // 设置通知优先级
                //.setAutoCancel(true) // 点击通知后自动取消
                .setOngoing(true)
                .build();
        // 启动前台服务
        startForeground(NOTIFICATION_ID, notification);
    }

    /**
     * 业务执行代码
     * */
    private void runMyCode() throws IntentFilter.MalformedMimeTypeException {
        try{
            /* 设立应用装卸监听器 */
            AppInstallReceiver.settingAppInstallReceiver(this);
            /* 设立MQ监听服务 */
            ReceiveMessageTask.startMQService(this);
            /*设立网络监听器*/
            NetworkChangeReceiver.startListening(this);
            /* 执行定时任务 */
            StayAliveService.schedulePeriodicWork(this);
        }catch (Exception e){
            JsonObject errorRequestParam = new JsonObject();
            OPPOSDKService opposdkService = new OPPOSDKService(this);
            errorRequestParam.addProperty(json_key_deviceCode.getValue(), CommonsUtils.getDeviceCode(opposdkService.getIMEI()));
            JSONParamPackingUtils.functionPacking(errorRequestParam,result_error,e.getMessage());
            //发送错误日志信息给后台
            new Thread(()->{
                HttpRequestUtils.retryHttpRequest(receiveTimedTask.getValue(), errorRequestParam.toString(), 200, 3, this);
            }).start();
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {
            createNotification();
            runMyCode();
        } catch (IntentFilter.MalformedMimeTypeException e) {
            throw new RuntimeException(e);
        }
        Log.w("常驻服务 MainActivityService","onStartCommand");
        // 处理服务启动的逻辑
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        /* 销毁应用装卸监听器 */
        AppInstallReceiver.removeAppInstallReceiver(this);
        /* 销毁MQ服务 */
        ReceiveMessageTask.stopMQService(this);
        /* 销毁网络监听器 */
        NetworkChangeReceiver.stopListening(this);
        /* 销毁定时任务 */
        StayAliveService.cancelAllWork(this);
        Log.w("常驻服务 MainActivityService","onDestroy");
        stopForeground(true);
    }

    /**
     * 添加后台常驻服务
     * */
    public static void startService(MainActivity mainActivity) {
        Log.w("常驻服务 MainActivityService","startService");
        mainActivity.startForegroundService(new Intent(mainActivity, MainActivityService.class));
    }

    /**
     * 摧毁后台常驻服务
     * */
    public static void stopMeService(Context context) {
        Log.w("常驻服务 MainActivityService","stopMeService");
        /*销毁常驻任务*/
        context.stopService(new Intent(context, MainActivityService.class));
    }


}
